<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>【JDK源码笔记】- HashMap红黑树 | 程序员小航</title><meta name="keywords" content="源码笔记,JDK"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="什么是红黑树？在HashMap中是怎么应用的？">
<meta property="og:type" content="article">
<meta property="og:title" content="【JDK源码笔记】- HashMap红黑树">
<meta property="og:url" content="https://liuzhihang.com/2020/05/25/source-code-hashmap-red-black-tree.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="什么是红黑树？在HashMap中是怎么应用的？">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree001.jpeg">
<meta property="article:published_time" content="2020-05-25T12:50:20.000Z">
<meta property="article:modified_time" content="2020-12-27T09:23:14.596Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="源码笔记">
<meta property="article:tag" content="JDK">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree001.jpeg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2020/05/25/source-code-hashmap-red-black-tree"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【JDK源码笔记】- HashMap红黑树',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-12-27 17:23:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree001.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【JDK源码笔记】- HashMap红黑树</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-05-25T12:50:20.000Z" title="发表于 2020-05-25 20:50:20">2020-05-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-12-27T09:23:14.596Z" title="更新于 2020-12-27 17:23:14">2020-12-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/JDK/">JDK</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【JDK源码笔记】- HashMap红黑树"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2020/05/25/source-code-hashmap-red-black-tree.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>前言<br>在阅读HashMap源码时，会发现在HashMap中使用了红黑树，所以需要先了解什么是红黑树，以及其原理。从而再进一步阅读HashMap中的链表到红黑树的转换，红黑树的增删节点等。</p>
</blockquote>
<blockquote>
<ol>
<li>什么是红黑树？</li>
<li>在HashMap中是怎么应用的？</li>
</ol>
</blockquote>
<h3 id="什么是红黑树？"><a href="#什么是红黑树？" class="headerlink" title="什么是红黑树？"></a>什么是红黑树？</h3><blockquote>
<p>红黑树（英语：Red–black tree）是一种自平衡二叉查找树，是在计算机科学中用到的一种数据结构，典型的用途是实现关联数组。它在1972年由鲁道夫·贝尔发明，被称为”对称二叉B树”，它现代的名字源于Leo J. Guibas和Robert Sedgewick于1978年写的一篇论文。红黑树的结构复杂，但它的操作有着良好的最坏情况运行时间，并且在实践中高效：它可以在O(logN)时间内完成查找、插入和删除，这里的n是树中元素的数目。</p>
</blockquote>
<h3 id="红黑树的性质"><a href="#红黑树的性质" class="headerlink" title="红黑树的性质"></a>红黑树的性质</h3><p>红黑树是每个节点都带有颜色属性的二叉查找树，颜色为红色或黑色。在二叉查找树强制一般要求以外，对于任何有效的红黑树我们增加了如下的额外要求：</p>
<ol>
<li>节点是红色或黑色。</li>
<li>根是黑色。</li>
<li>所有叶子都是黑色（叶子是NIL节点）。</li>
<li>每个红色节点必须有两个黑色的子节点。（从每个叶子到根的所有路径上不能有两个连续的红色节点。）</li>
<li>从任一节点到其每个叶子的所有简单路径都包含相同数目的黑色节点。</li>
</ol>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree001.jpeg" alt="红黑树001"></p>
<h3 id="红黑树操作"><a href="#红黑树操作" class="headerlink" title="红黑树操作"></a>红黑树操作</h3><h4 id="左旋、右旋"><a href="#左旋、右旋" class="headerlink" title="左旋、右旋"></a>左旋、右旋</h4><p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/krck8S.gif" alt="krck8S"></p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/OUd2GL.gif" alt="OUd2GL"></p>
<h4 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h4><ol>
<li>以二叉查找树的方法增加节点</li>
<li>新插入节点为红色（如果设为黑色，就会导致根到叶子的路径上有一条路上，多一个额外的黑节点，这个是很难调整的。但是设为红色节点后，可能会导致出现两个连续红色节点的冲突，那么可以通过颜色调换（color flips）和树旋转来调整。）</li>
</ol>
<p>注意：</p>
<ol>
<li>性质1和性质3是永远保持着的。</li>
<li>性质4只在增加红色节点、重绘黑色节点为红色，或做旋转时受到威胁。</li>
<li>性质5只在增加黑色节点、重绘红色节点为黑色，或做旋转时受到威胁。</li>
</ol>
<p>插入时会遇到以下五种情形：</p>
<blockquote>
<p>情形1：插入第一个节点<br>情形2：插入新节点，父节点是黑色<br>情形3：插入新节点，父节点是红色，叔父节点是红色<br>情形4：插入新节点，父节点是红色，叔父节点是黑色或缺省，新节点是右子节点，父节点又是其父节点的左子节点<br>情形5：插入新节点，父节点是红色，叔父节点是黑色或缺省，新节点是左子节点，父节点又是其父节点的左子节点。</p>
</blockquote>
<ul>
<li>情形1：</li>
</ul>
<p>操作：插入第一个节点<br>违反性质2：” 根是黑色。 “<br>情形：直接插入红色节点，然后进行染色为黑色</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree1.gif" alt="红黑树1"></p>
<ul>
<li>情形2：</li>
</ul>
<p>操作：插入新节点，父节点是黑色<br>未违反性质<br>情形：直接插入</p>
<ul>
<li>情形3：</li>
</ul>
<p>操作：插入新节点，父节点是红色，叔父节点是红色<br>违反性质4：” 每个红色节点必须有两个黑色的子节点。 “<br>情形：将祖父节点染色，祖父节点染色后再进行重新判断进行染色或旋转</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree3.gif" alt="红黑树3"></p>
<ul>
<li>情形4：</li>
</ul>
<p>操作：插入新节点，父节点是红色，叔父节点是黑色或缺省，新节点是右子节点，父节点又是其父节点的左子节点<br>违反性质4：” 每个红色节点必须有两个黑色的子节点。 “<br>情形：进行左旋，旋转后父节点变成左子节点，新节点变成父节点，然后重新判断进行染色或旋转</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree4.gif" alt="红黑树4"></p>
<ul>
<li>情形5：</li>
</ul>
<p>操作：插入新节点，父节点是红色，叔父节点是黑色或缺省，新节点是左子节点，父节点又是其父节点的左子节点。<br>违反性质4：” 每个红色节点必须有两个黑色的子节点。 “<br>情形：父节点染色为黑色，进行右旋，祖父节点变为右子节点，然后重新判断进行染色或旋转</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree5.gif" alt="红黑树5"></p>
<h3 id="HashMap"><a href="#HashMap" class="headerlink" title="HashMap"></a>HashMap</h3><h4 id="结构"><a href="#结构" class="headerlink" title="结构"></a>结构</h4><pre><code class="java">static final class TreeNode&lt;K,V&gt; extends LinkedHashMap.Entry&lt;K,V&gt; &#123;
    TreeNode&lt;K,V&gt; parent;  // red-black tree links
    TreeNode&lt;K,V&gt; left;
    TreeNode&lt;K,V&gt; right;
    TreeNode&lt;K,V&gt; prev;    // needed to unlink next upon deletion
    boolean red;
    // ... 省略
&#125;</code></pre>
<h4 id="三个参数"><a href="#三个参数" class="headerlink" title="三个参数"></a>三个参数</h4><pre><code class="java">/**
 * 链表转为树阈值。 
 * 大于等于8时，会转换为树。 
 * 8 是综合性能考虑确定的值
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 从树转换为链表的阈值
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 最小树形化容量，只有哈希表元素数到达64才会进行树转换
 */
static final int MIN_TREEIFY_CAPACITY = 64;</code></pre>
<h4 id="链表转红黑树-treeifyBin"><a href="#链表转红黑树-treeifyBin" class="headerlink" title="链表转红黑树-treeifyBin"></a>链表转红黑树-treeifyBin</h4><ol>
<li>数组（哈希表）长度到达64</li>
<li>当链表长度大于等于8是会将链表转换为红黑树</li>
</ol>
<pre><code class="java">final void treeifyBin(Node&lt;K,V&gt;[] tab, int hash) &#123;
    int n, index; Node&lt;K,V&gt; e;
    // 数组为null或者数组长度小于MIN_TREEIFY_CAPACITY（64）时，进行扩容
    if (tab == null || (n = tab.length) &lt; MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) &amp; hash]) != null) &#123;
        // 头尾节点 hd-头 tl-尾
        TreeNode&lt;K,V&gt; hd = null, tl = null;
        do &#123;
            // 创建树节点 Node -&gt; TreeNode
            // 循环执行完之后得到的是双向链表
            TreeNode&lt;K,V&gt; p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else &#123;
                p.prev = tl;
                tl.next = p;
            &#125;
            tl = p;
        &#125; while ((e = e.next) != null);
        // 此时得到的仅仅是双向链表
        // 指针指向链表头
        if ((tab[index] = hd) != null)
            // 将双向链表转换为树
            hd.treeify(tab);
    &#125;
&#125;
</code></pre>
<pre><code class="java">final void treeify(Node&lt;K,V&gt;[] tab) &#123;
    TreeNode&lt;K,V&gt; root = null;
    for (TreeNode&lt;K,V&gt; x = this, next; x != null; x = next) &#123;
        next = (TreeNode&lt;K,V&gt;)x.next;
        x.left = x.right = null;
        if (root == null) &#123;
            // 情形1：插入第一个节点
            x.parent = null;
            x.red = false;
            root = x;
        &#125;
        else &#123;
            // 当前节点的 key 和 hash
            K k = x.key;
            int h = x.hash;
            Class&lt;?&gt; kc = null;
            // 再次循环
            for (TreeNode&lt;K,V&gt; p = root;;) &#123;
                int dir, ph;
                // 内层循环的key
                K pk = p.key;
                // 当前节点的hash和内层循环的hash值作比较
                if ((ph = p.hash) &gt; h)
                    // &lt; 0 left查找
                    dir = -1;
                else if (ph &lt; h)
                    // &gt; 0 right 查找
                    dir = 1;
                else if ((kc == null &amp;&amp;
                            (kc = comparableClassFor(k)) == null) ||
                            (dir = compareComparables(kc, k, pk)) == 0)
                    // 比较对象
                    dir = tieBreakOrder(k, pk);

                TreeNode&lt;K,V&gt; xp = p;
                // dir &lt;= 0 则走 left查找 &gt; 0 则走 right查找
                if ((p = (dir &lt;= 0) ? p.left : p.right) == null) &#123;
                    x.parent = xp;
                    if (dir &lt;= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    // 正式转换为红黑树
                    root = balanceInsertion(root, x);
                    break;
                &#125;
            &#125;
        &#125;
    &#125;
    moveRootToFront(tab, root);
&#125;</code></pre>
<pre><code class="java">
// root 根节点
// x 要操作的节点
static &lt;K,V&gt; TreeNode&lt;K,V&gt; balanceInsertion(TreeNode&lt;K,V&gt; root, TreeNode&lt;K,V&gt; x) &#123;
    // 默认节点为红色
    x.red = true;
    // xp：x的父节点
    // xpp：x的祖父节点
    // xppl：x祖父节点的左子节点
    // xppr：x祖父节点的右子节点
    for (TreeNode&lt;K,V&gt; xp, xpp, xppl, xppr;;) &#123;

        // 情形1： 父节点为null， 直接置为根
        if ((xp = x.parent) == null) &#123;
            x.red = false;
            return x;
        &#125;
        // 父节点黑色 或者 祖父节点为空，直接返回
        // 情形2：插入新节点，父节点是黑色
        else if (!xp.red || (xpp = xp.parent) == null)
            return root;

        // 父节点是祖父节点的左子节点
        if (xp == (xppl = xpp.left)) &#123;
            // 祖父节点的右子节点不为空且是红色
            // 情形3：插入新节点，父节点是红色，叔父节点是红色
            if ((xppr = xpp.right) != null &amp;&amp; xppr.red) &#123;
                xppr.red = false; //祖父节点的右子节点设置为黑色
                xp.red = false; // 父节点设置为黑色
                xpp.red = true; // 祖父节点设置为红色
                x = xpp; // 继续操作祖父节点
            &#125;
            // 旋转
            else &#123;
                // 新插入的是右子节点
                if (x == xp.right) &#123;
                    // 插入的x是父节点的右子节点， 进行左旋
                    root = rotateLeft(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                &#125;
                if (xp != null) &#123;
                    // 父节点设置为黑色
                    xp.red = false;
                    if (xpp != null) &#123;
                        xpp.red = true;
                        // 右旋
                        root = rotateRight(root, xpp);
                    &#125;
                &#125;
            &#125;
        &#125;
        // 父节点是祖父节点的右子节点
        else &#123;
            // 祖父节点的左子节点不为空且为红色
            if (xppl != null &amp;&amp; xppl.red) &#123;
                xppl.red = false; // 祖父节点的左子节点设置为黑色
                xp.red = false; // 父节点设置为黑色
                xpp.red = true; // 祖父节点设置为红色
                x = xpp; // 继续操作祖父节点
            &#125;
            // 旋转
            else &#123;
                if (x == xp.left) &#123;
                    root = rotateRight(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                &#125;
                if (xp != null) &#123;
                    xp.red = false;
                    if (xpp != null) &#123;
                        xpp.red = true;
                        root = rotateLeft(root, xpp);
                    &#125;
                &#125;
            &#125;
        &#125;
    &#125;
&#125;</code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2020/05/25/source-code-hashmap-red-black-tree.html">https://liuzhihang.com/2020/05/25/source-code-hashmap-red-black-tree.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><a class="post-meta__tags" href="/tags/JDK/">JDK</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/red-black-tree001.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/06/12/source-code-cas.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div><div class="next-post pull-right"><a href="/2020/05/17/source-code-hashmap-resize.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/GRQHSY.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【JDK源码笔记】- HashMap扩容</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/12/source-code-aqs.html" title="【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/aqs-uhgQnu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-12</div><div class="title">【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)</div></div></a></div><div><a href="/2020/09/27/source-code-arrayblockingqueue.html" title="【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ArrayBlockingQueue-cover-ESuNmo.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-27</div><div class="title">【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue</div></div></a></div><div><a href="/2020/06/12/source-code-cas.html" title="【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-12</div><div class="title">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E7%BA%A2%E9%BB%91%E6%A0%91%EF%BC%9F"><span class="toc-text">什么是红黑树？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BA%A2%E9%BB%91%E6%A0%91%E7%9A%84%E6%80%A7%E8%B4%A8"><span class="toc-text">红黑树的性质</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BA%A2%E9%BB%91%E6%A0%91%E6%93%8D%E4%BD%9C"><span class="toc-text">红黑树操作</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B7%A6%E6%97%8B%E3%80%81%E5%8F%B3%E6%97%8B"><span class="toc-text">左旋、右旋</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8F%92%E5%85%A5"><span class="toc-text">插入</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HashMap"><span class="toc-text">HashMap</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%93%E6%9E%84"><span class="toc-text">结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E4%B8%AA%E5%8F%82%E6%95%B0"><span class="toc-text">三个参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%93%BE%E8%A1%A8%E8%BD%AC%E7%BA%A2%E9%BB%91%E6%A0%91-treeifyBin"><span class="toc-text">链表转红黑树-treeifyBin</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: '6a36cfe55fca04281b70bd83c6467fdd',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>